/*
  Name: Records.cpp
  Copyright: 
  Author: Hank Stalica
  Date: 29/12/09 03:14
  Description: The implementation of the Records class.
*/

#ifndef RECORDS_CPP
#define RECORDS_CPP

#include "Records.h"

#include <iostream>
using std::cout;
using std::endl;

#include <fstream>
using std::ofstream;
using std::ifstream;

Records::Records(){
}

int Records::store(Record r){ //stores a record in the record vector.
//Utilizes insertion sort algorithm to keep records sorted by
//stock symbol (alphabetically)

  if (records.size() == 0) { //If there are no records, add one.
		records.push_back(r);
		return 0;
  }
  
  int pos = 0;
  vector<Record>::iterator p;
  for (p = records.begin(); p != records.end(); p++, pos++){ //Traverse the vector
		if (r < records[pos]) {  //If new record < record at current position,
			records.insert(p, r);  //insert it.
			return 0;
		}
		if (r == records[pos]) { //If new record == record at current position,
      records[pos] = r;     //  update it.
      return 0;
    }
  }
  return -1; //If we got here, something went wrong.
}

//Retrieve a record by stock symbol.
int Records::retrieve(Record& r, string s){ //retrieves a specific record.
  for (unsigned int i = 0; i < records.size(); i++){
    if (s == records[i].getSymbol()){
       r = records[i];
       return 0;
    }
  }
  return -1;
}

//Wrapper function for inserting a record into Records vector.
int Records::store(string a, string b, string c, string d, string e, string f,
  string g, string h, string i){
  if (a != "") {
    Record r(a, b, c, d, e, f, g, h, i);
    store(r);
  }
}

string Records::retrieveAll(){ //retrieves all records as a string.
  string s;
  for (unsigned int i = 0; i < records.size(); i++){
    s += records[i].getRecord() + "\r\n";
  }
  return s;
}

int Records::save() { //saves all records to disk.
  if (records.size() == 0) return -1; //If there aren't records, no point in saving.
  ofstream fout;
  fout.open("records.dat");
  if (fout.is_open()){
    for (unsigned int i = 0; i < records.size(); i++){
      fout << records[i] << endl;
    }
    fout.close();
    return 0;
  }
  return -2; //Failed to save.
}

/*
int Records::load() { //loads all records from disk.
  char buffer[_BUFLEN];
  ifstream fin;
  fin.open("records.dat");
  if (fin.is_open()){
    while(fin.getline(buffer, _BUFLEN)){
      records.push_back(buffer);
    }
  }
}
*/
#endif
